<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link rel="stylesheet" href="./app.css">
</head>

<body>
  <div class="container">
    <img src="./a.jpg" alt="" width="100%">
    <div class="move">
      <img src="./a.jpg" alt="">
    </div>
  </div>

  <script>
    // 获取元素的对象
    const container = document.querySelector('.container');
    const move = document.querySelector('.move');
    const bigImg = document.querySelector('.move img');

    // 绑定container 的鼠标移动事件
    container.addEventListener('mousemove', (e) => {
      // 获取鼠标距离左侧的偏移
      let x = e.clientX;
      console.log("鼠标距离左侧的偏移:"+x)
      // 获取container距离左侧的一个偏移
      let l = container.offsetLeft;
      console.log("container距离左侧的一个偏移:"+l)
      // 计算最终的left值
      let moveLeft = x - l - move.offsetWidth / 2;
      // 边界检测
      if (moveLeft <= -move.offsetWidth / 2) moveLeft = -move.offsetWidth / 2;
      let maxLeft = container.offsetWidth - move.offsetWidth + move.offsetWidth / 2;
      if (moveLeft >= maxLeft) moveLeft = maxLeft;
      //设置样式
      move.style.left = moveLeft + 'px';
      // 计算大图的left的值
      let bigImgLeft = (moveLeft + move.offsetWidth / 2) / container.offsetWidth * bigImg.offsetWidth - move.offsetWidth / 2;
      // 设置img left的值
      bigImg.style.left = - bigImgLeft + 'px';

      let y = e.clientY;
      let t = container.offsetTop;
      let moveTop = y - t - move.offsetHeight / 2;
      if (moveTop <= -move.offsetHeight / 2) moveTop = -move.offsetHeight / 2;
      let maxTop = container.offsetHeight - move.offsetHeight + move.offsetHeight / 2;
      if (moveTop >= maxTop) moveTop = maxTop;
      move.style.top = moveTop + 'px';
      let bigImgTop = (moveTop + move.offsetHeight / 2) / container.offsetHeight * bigImg.offsetHeight - move.offsetHeight / 2;
      bigImg.style.top = - bigImgTop + 'px';
    })

  </script>
</body>

</html>